import type { IMiddleware } from "koa-router";

import { Article, ArticleLog } from "../model";
import { ArticleStatus } from "../model/article";
import { makeResponse, HttpStatusCode } from "../util/response";

// 获取所有文章
export const getArticles: IMiddleware = async ctx => {
  // 1. 获取 query 参数
  const current = ctx.query.current as any as number;
  const limit = ctx.query.limit as any as number;
  const status = ctx.query.status as any as ArticleStatus;
  const title = ctx.query.title as string;
  const sort = (ctx.query.sort as any as number) ?? -1;
  const userId = ctx.query.userId as string;

  
  // 1.1 获取前面拿到的 total
  const { total } = ctx.state;
  let result: any[] = [];
  if (total !== 0) {
    // 2. 连接数据库获取 articles
    const skipCount = (current - 1) * limit;
    const query = Article.find({})
      .skip(skipCount)
      .limit(limit)
      .populate({ path: "author", select: "name" })
      .sort({ create_at: sort });

    // 2.1 根据参数筛选数据
    if (title) query.where("title").regex(title);
    if (status) query.where("status").equals(status);
    if (userId) query.where("author").equals(userId);
    result = await query;
  }
  // 3. 返回所有 articles 包括 total
  makeResponse(ctx, HttpStatusCode.Ok, { result, total });
};

// 获取单个文章
export const getArticle: IMiddleware = async ctx => {
  const { id } = ctx.params;
  const result = await Article.findById(id).populate({
    path: "author",
    select: "name"
  });

  makeResponse(ctx, HttpStatusCode.Ok, result);
};

// 更新文章状态
export const updateArticleStatus: IMiddleware = async ctx => {
  const { id } = ctx.params;
  const { status } = ctx.request.body;
  await Article.findByIdAndUpdate(id, { status });
  const result = await Article.findById(id).populate({
    path: "author",
    select: "name"
  });

  const { adminId } = ctx.state.jwtdata;
  // 记录操作
  const log = new ArticleLog({
    article: id,
    create_by: adminId,
    operation: status
  });
  await log.save();

  makeResponse(ctx, HttpStatusCode.Ok, result);
};

// 删除文章
export const deleteArticle: IMiddleware = async ctx => {
  const { id } = ctx.params;
  await Article.findByIdAndDelete(id);

  makeResponse(ctx, HttpStatusCode.NoContent);
};

// test 新增文章
export const createArticle: IMiddleware = async ctx => {
  const article = new Article(ctx.request.body);
  await article.save();

  makeResponse(ctx, HttpStatusCode.Ok, article);
};
